package com.white.loggerserver.logpop;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.qw.soul.permission.SoulPermission;
import com.qw.soul.permission.bean.Special;
import com.qw.soul.permission.callbcak.SpecialPermissionListener;
import com.white.loggerserver.MainActivity;
import com.white.loggerserver.R;
import com.white.loggerserver.utils.UiHelper;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

/**
 * Created by ytf on 2019/07/22.
 * Description:
 */
public class GlobleWindow implements View.OnClickListener
{
    private SmallWindowView windowView;
    private RecyclerView logRecycle;
    private View close, clear,app, widExpand, widShrink, heiExpand, heiShrink;

    private ClipboardManager manager;
    private TextView tip;

    private WindowManager wm;
    private WindowManager.LayoutParams mLayoutParams;

    private Context mContext;

    private Ad adapter;

    private Vector<LogBean> datas = new Vector<>();
    private LinearLayoutManager mLayoutManager;

    public GlobleWindow(Context mContext)
    {
        this.mContext = mContext;
        initSmallViewLayout();

        adapter = new Ad(datas);
        mLayoutManager = new LinearLayoutManager(mContext);
        logRecycle.setLayoutManager(mLayoutManager);
        logRecycle.setAdapter(adapter);

        manager = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
    }

    private void initSmallViewLayout()
    {
        windowView = (SmallWindowView) LayoutInflater.from(mContext).inflate(R.layout.gloable_pop, null);
        logRecycle = windowView.findViewById(R.id.log_recycle);
        tip = windowView.findViewById(R.id.tip);

        close = windowView.findViewById(R.id.close);
        clear = windowView.findViewById(R.id.clear);
        app = windowView.findViewById(R.id.app);

        close.setOnClickListener(this);
        clear.setOnClickListener(this);
        app.setOnClickListener(this);

        widExpand = windowView.findViewById(R.id.wid_expand);
        widShrink = windowView.findViewById(R.id.wid_shrink);
        heiExpand = windowView.findViewById(R.id.hei_expand);
        heiShrink= windowView.findViewById(R.id.hei_shrink);

        widExpand.setOnClickListener(this);
        widShrink.setOnClickListener(this);
        heiExpand.setOnClickListener(this);
        heiShrink.setOnClickListener(this);

        wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        mLayoutParams = new WindowManager.LayoutParams();
        int sw = UiHelper.screenWidth(mContext);
        int sh = UiHelper.screenHeight(mContext);
        mLayoutParams.width = (int) (sw * (sw > sh ? 0.6 : 0.8f));
        mLayoutParams.height = (int) (mLayoutParams.width * (sw > sh ? 0.6f : 1.2f));
        mLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        mLayoutParams.format = PixelFormat.TRANSLUCENT;
        //可使用FLAG_DISMISS_KEYGUARD选项直接解除非加锁的锁屏状态。此选项只用于最顶层的全屏幕窗口。
        mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL //不耽误其他事件
                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;

        mLayoutParams.gravity = Gravity.START | Gravity.TOP;
        //使用非CENTER时，可以通过设置XY的值来改变View的位置
        windowView.setWm(wm);
    }

    private Callback mCallback;

    public void setCallback(Callback mCallback) {
        this.mCallback = mCallback;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.close:
                dismissWindow();
                if(mCallback != null){
                    mCallback.onDismiss();
                }
                break;
            case R.id.clear:
                clear();
                break;
            case R.id.app:
                Intent it = new Intent(mContext, MainActivity.class);
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
                mContext.startActivity(it);
                break;
            case R.id.wid_expand:
                windowView.updateWid(20);
                break;
            case R.id.wid_shrink:
                windowView.updateWid(-20);
                break;
            case R.id.hei_expand:
                windowView.updateHei(20);
                break;
            case R.id.hei_shrink:
                windowView.updateHei(-20);
                break;
        }
    }

    public interface Callback{
        void onDismiss();
    }

    public void show()
    {
        SoulPermission.getInstance()
                .checkAndRequestSpecialPermission(Special.DRAW_WINDOW, new SpecialPermissionListener()
                {
                    @Override
                    public void onGranted(Special permission)
                    {
                        alertWindow();
                    }

                    @Override
                    public void onDenied(Special permission)
                    {
                        Toast.makeText(mContext, "弹窗权限被拒绝", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private boolean isShowing;

    private void alertWindow()
    {
        if(isShowing) return;

        // 7.0 以上需要引导用去设置开启窗口浮动权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            // 8.0 以上type需要设置成这个
            mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }
        wm.addView(windowView, mLayoutParams);
        windowView.setWmParams(mLayoutParams);
        isShowing = true;
    }

    // 移除window
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void dismissWindow()
    {
        if (wm != null && windowView != null && windowView.getWindowId() != null)
        {
            wm.removeView(windowView);
        }
        isShowing = false;
    }


    public void postItem(LogBean bean)
    {
        datas.add(bean);
        if(wm != null && windowView != null)
        {
            if(datas.size() >= 100){
                datas.clear();
                adapter.notifyItemRangeRemoved(0, 100);
            }else{
                adapter.notifyItemInserted(adapter.getItemCount());
            }

            int count = adapter.getItemCount();
            if(count > 0)
            {
                scrollToPosition(adapter.getItemCount()-1);
            }
        }
    }

    private synchronized void clear()
    {
        datas.clear();
        adapter.notifyDataSetChanged();
    }

    private void scrollToPosition(int posi)
    {
        LinearSmoothScroller s1 = new TopSmoothScroller(mContext);
        s1.setTargetPosition(posi);
        mLayoutManager.startSmoothScroll(s1);
    }

    private static class TopSmoothScroller extends LinearSmoothScroller
    {
        TopSmoothScroller(Context context)
        {
            super(context);
        }

        @Override
        protected int getHorizontalSnapPreference()
        {
            return SNAP_TO_START;//具体见源码注释
        }

        @Override
        protected int getVerticalSnapPreference()
        {
            return SNAP_TO_START;//具体见源码注释
        }
    }

    class Ad extends BaseQuickAdapter<LogBean, BaseViewHolder>
    {

        public Ad(List<LogBean> data)
        {
            super(R.layout.gloable_pop_item, data);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder holder, LogBean logBean) {
            TextView tv = holder.getView(R.id.desc);
            tv.setTextColor(logBean.fontColor);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, logBean.fontSize);
            tv.setBackgroundColor(logBean.bgColor);
            tv.setText(logBean.content);
        }
    }
}
